package com.xudm.cdg.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.enums.CellExtraTypeEnum;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.CellExtra;
import com.xudm.cdg.entity.cosmic.CosmicExcelModel;
import lombok.Getter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * cosmic文档数据监听
 *
 * @author xudm
 */
@Getter
public class CosmicExcelModelDataListener extends AnalysisEventListener<CosmicExcelModel> {
    private List<CosmicExcelModel> dataList = new ArrayList<>();
    private List<CellExtra> mergeInfoList = new ArrayList<>();
    private Map<Integer, Integer> rowIndexMap = new HashMap<>(); // 用于记录行号和dataList索引的映射

    @Override
    public void invoke(CosmicExcelModel data, AnalysisContext context) {
        int currentRowIndex = context.readRowHolder().getRowIndex();
        rowIndexMap.put(currentRowIndex, dataList.size());
        dataList.add(data);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 填充合并单元格的值到所有相关的单元格中
        mergeInfoList.stream().collect(Collectors.groupingBy(CellExtra::getFirstColumnIndex)).forEach((colIndex, colMergeInfoList) -> {
            for (CellExtra cellExtra : colMergeInfoList) {
                int firstRow = cellExtra.getFirstRowIndex();
                int lastRow = cellExtra.getLastRowIndex();
                int firstCol = cellExtra.getFirstColumnIndex();
                int lastCol = cellExtra.getLastColumnIndex();

                // 获取合并单元格的值
                Integer firstRowIndexInDataList = rowIndexMap.get(firstRow);
                if (firstRowIndexInDataList == null) {
                    continue; // 如果找不到对应的行，跳过
                }
                CosmicExcelModel firstRowData = dataList.get(firstRowIndexInDataList);
                String valueToFill = getValueByColumnIndex(firstRowData, colIndex);

                // 填充合并单元格的值到所有相关的单元格中
                for (int row = firstRow; row <= lastRow; row++) {
                    Integer rowIndexInDataList = rowIndexMap.get(row);
                    if (rowIndexInDataList == null) {
                        continue; // 如果找不到对应的行，跳过
                    }
                    CosmicExcelModel rowData = dataList.get(rowIndexInDataList);
                    setValueByColumnIndex(rowData, colIndex, valueToFill);
                }
            }
        });


//        for (CellExtra extra : mergeInfoList) {
//            int firstRow = extra.getFirstRowIndex();
//            int lastRow = extra.getLastRowIndex();
//            int firstCol = extra.getFirstColumnIndex();
//            int lastCol = extra.getLastColumnIndex();
//
//            // 获取合并单元格的值
//            Integer firstRowIndexInDataList = rowIndexMap.get(firstRow);
//            if (firstRowIndexInDataList == null) {
//                continue; // 如果找不到对应的行，跳过
//            }
//            CosmicExcelModel firstRowData = dataList.get(firstRowIndexInDataList);
//            String valueToFill = getValueByColumnIndex(firstRowData, firstCol);
//
//            // 填充合并单元格的值到所有相关的单元格中
//            for (int row = firstRow; row <= lastRow; row++) {
//                Integer rowIndexInDataList = rowIndexMap.get(row);
//                if (rowIndexInDataList == null) {
//                    continue; // 如果找不到对应的行，跳过
//                }
//                CosmicExcelModel rowData = dataList.get(rowIndexInDataList);
//                for (int col = firstCol; col <= lastCol; col++) {
//                    setValueByColumnIndex(rowData, col, valueToFill);
//                }
//            }
//        }
    }

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        super.invokeHeadMap(headMap, context);
        // 校验表头
        if (!"模块".equals(headMap.get(0)) || !"客户需求".equals(headMap.get(1)) || !"功能用户".equals(headMap.get(2))
                || !"功能性用户需求".equals(headMap.get(3)) || !"触发事件".equals(headMap.get(4)) || !"功能处理".equals(headMap.get(5))
                || !"子功能处理".equals(headMap.get(6)) || !"数据移动类型".equals(headMap.get(7)) || !"数据组".equals(headMap.get(8))
                || !"数据属性".equals(headMap.get(9)) || !"复用度".equals(headMap.get(10))) {
            throw new RuntimeException("表头校验失败，表头不符合预期, 请检查模板是否正确,表头缺少模块列");
        }
    }

    /**
     * 根据列索引获取值
     *
     * @param data     数据
     * @param colIndex 列索引
     * @return 值
     */
    private String getValueByColumnIndex(CosmicExcelModel data, int colIndex) {
        return switch (colIndex) {
            case 0 -> data.getModelName();
            case 1 -> data.getCustomerDemand();
            case 2 -> data.getFunctionalUser();
            case 3 -> data.getFunctionalUserDemand();
            case 4 -> data.getTriggerEvent();
            case 5 -> data.getFunctionalProcessing();
            case 6 -> data.getSubFunctionalProcessing();
            case 7 -> data.getDataMovementType();
            case 8 -> data.getDataGroup();
            case 9 -> data.getDataAttribute();
            case 10 -> data.getReuseDegree();
            case 11 -> data.getCfp();
            case 12 -> data.getSummary();
            case 13 -> data.getPlatform();
            case 14 -> data.getStratification();
            case 15 -> data.getWriter();
            case 16 -> data.getProductPrincipal();
            case 17 -> data.getDeveloper();
            case 18 -> data.getAuditor();
            case 19 -> data.getDocumentWriter();
            default -> throw new IllegalArgumentException("Invalid column index: " + colIndex);
        };
    }

    /**
     * 根据列索引设置值
     *
     * @param data     数据
     * @param colIndex 列索引
     * @param value    值
     */
    private void setValueByColumnIndex(CosmicExcelModel data, int colIndex, String value) {
        switch (colIndex) {
            case 0:
                data.setModelName(value);
                break;
            case 1:
                data.setCustomerDemand(value);
                break;
            case 2:
                data.setFunctionalUser(value);
                break;
            case 3:
                data.setFunctionalUserDemand(value);
                break;
            case 4:
                data.setTriggerEvent(value);
                break;
            case 5:
                data.setFunctionalProcessing(value);
                break;
            case 6:
                data.setSubFunctionalProcessing(value);
                break;
            case 7:
                data.setDataMovementType(value);
                break;
            case 8:
                data.setDataGroup(value);
                break;
            case 9:
                data.setDataAttribute(value);
                break;
            case 10:
                data.setReuseDegree(value);
                break;
            case 11:
                data.setCfp(value);
                break;
            case 12:
                data.setSummary(value);
                break;
            case 13:
                data.setPlatform(value);
                break;
            case 14:
                data.setStratification(value);
                break;
            case 15:
                data.setWriter(value);
                break;
            case 16:
                data.setProductPrincipal(value);
                break;
            case 17:
                data.setDeveloper(value);
                break;
            case 18:
                data.setAuditor(value);
                break;
            case 19:
                data.setDocumentWriter(value);
                break;
            default:
                throw new IllegalArgumentException("Invalid column index: " + colIndex);
        }
    }

    @Override
    public void extra(CellExtra extra, AnalysisContext context) {
        if (extra.getType() == CellExtraTypeEnum.MERGE) {
            mergeInfoList.add(extra);
        }
    }

}
